package com.xr.miniprogram.tools.RedissonUtil;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.xr.common.enums.RedisDelayQueueEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述: 启动延迟队列监测扫描
 */
@Slf4j
@Component
public class RedisDelayQueueStarter{
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;
    @Autowired
    private ApplicationContext context;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    private final long period = 500L;

    /**
     * 线程池，维护keyAliveTime，自定义任务调度
     */
    private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(1,
            new ThreadFactoryBuilder().setNameFormat("queue-delay-%d").setDaemon(true).build());

    //在Spring容器的启动时自动执行
    @PostConstruct
    public void run(){
        // 定时任务，每秒执行一次「续时」操作
        SCHEDULER.scheduleAtFixedRate(() -> {
            RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();//将枚举类变成枚举数组
            for (RedisDelayQueueEnum queueEnum : queueEnums) {
                Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
                if (value != null) {
                    RedisDelayQueueHandle<Object> redisDelayQueueHandle = (RedisDelayQueueHandle<Object>)context.getBean(queueEnum.getBeanId());
                    taskExecutor.execute(() -> {redisDelayQueueHandle.execute(value);});
                    //redisDelayQueueHandle.execute(value);
                }
            }

        }, 0, period, TimeUnit.MILLISECONDS);

        log.info("====================Redission延迟队列监测启动成功====================");

    }
}